﻿using System;
using System.Windows;
using System.Windows.Threading;
using Wp7Tools.ViewServices;

namespace Wp7Tools {
    public class ViewModelBase : ObservableObject {
    	private bool _isBusy;
		private bool _notifyUsingDispatcher = true;
		private INavigationService _navigationService = ViewServices.NavigationService.Default;

		public bool IsBusy {
			get { return _isBusy; }
			set { 
				_isBusy = value;
				RaisePropertyChanged(() => IsBusy);
			}
		}

    	public bool NotifyUsingDispatcher {
    		get { return _notifyUsingDispatcher; }
    		set { _notifyUsingDispatcher = value; }
    	}

        public INavigationService NavigationService {
            get { return _navigationService; }
            set { _navigationService = value; }
        }

    	protected Dispatcher Dispatcher {
    		get { return Deployment.Current.Dispatcher; }
    	}

		protected override void RaisePropertyChanged<T>(System.Linq.Expressions.Expression<Func<T>> propertyExpression) {
			if(!NotifyUsingDispatcher || Dispatcher.CheckAccess()) {
				base.RaisePropertyChanged(propertyExpression);
				return;
			}
			Dispatcher.BeginInvoke(() => RaisePropertyChangedToAvoidCs1911(propertyExpression));
		}

		//http://msdn.microsoft.com/en-us/library/ms228459(v=vs.90).aspx
		private void RaisePropertyChangedToAvoidCs1911<T>(System.Linq.Expressions.Expression<Func<T>> propertyExpression) {
			base.RaisePropertyChanged(propertyExpression);
		}
    }
}